package com.shop.loan.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shop.loan.mapper.LoanOrderByMybatisMapper;
import com.shop.loan.mapper.UserByMybatisMapper;
import com.shop.loan.model.entity.LoanOrderByMybatis;
import com.shop.loan.model.entity.UserByMybatis;
import com.shop.loan.model.vo.LoanOrderRemarkVo;
import org.springframework.stereotype.Service;
import xyz.erupt.annotation.fun.OperationHandler;

import javax.annotation.Resource;
import java.util.List;

@Service
public class LoanOrderRemarkHandler implements OperationHandler<Object, LoanOrderRemarkVo> {

    @Resource
    LoanOrderByMybatisMapper loanOrderByMybatisMapper;

    @Resource
    UserByMybatisMapper userByMybatisMapper;

    @Override
    public String exec(List<Object> data, LoanOrderRemarkVo loanOrderRemarkVo, String[] param) {
        Object item = data.get(0);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(item));
        Long id = jsonObject.getLongValue("id");
        Long userId = jsonObject.getLongValue("userId");

        if (loanOrderRemarkVo.getUserStatus() != null) {
            UserByMybatis userByMybatis = new UserByMybatis();
            userByMybatis.setId(userId);
            userByMybatis.setMachineStatus(loanOrderRemarkVo.getUserStatus() != 1);
            userByMybatisMapper.updateByPrimaryKeySelective(userByMybatis);
        }

        LoanOrderByMybatis updateOrder = new LoanOrderByMybatis();
        updateOrder.setId(id);
        updateOrder.setUserWill(loanOrderRemarkVo.getUserWill());
        updateOrder.setRemark(loanOrderRemarkVo.getRemark());
        loanOrderByMybatisMapper.updateByPrimaryKeySelective(updateOrder);
        return null;
    }

    @Override
    public LoanOrderRemarkVo eruptFormValue(List<Object> data, LoanOrderRemarkVo loanOrderRemarkVo, String[] param) {
        Object item = data.get(0);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(item));
        Long id = jsonObject.getLongValue("id");

        LoanOrderByMybatis loanOrderByMybatis = loanOrderByMybatisMapper.selectByPrimaryKey(id);
        if (loanOrderByMybatis != null) {
            loanOrderRemarkVo.setRemark(loanOrderByMybatis.getRemark() == null ? "" : loanOrderByMybatis.getRemark());
            loanOrderRemarkVo.setUserWill(loanOrderByMybatis.getUserWill() == null ? 1 : loanOrderByMybatis.getUserWill());
        }
        UserByMybatis userByMybatis = userByMybatisMapper.selectByPrimaryKey(loanOrderByMybatis.getUserId());
        System.out.println(userByMybatis);
        if(userByMybatis != null){
            if(userByMybatis.getMachineStatus() != null && userByMybatis.getMachineStatus()){
                loanOrderRemarkVo.setUserStatus(2);
            }else{
                loanOrderRemarkVo.setUserStatus(1);
            }
        }
        return loanOrderRemarkVo;
    }
}
